package org.helsoft.mojo;

import java.io.File;
import java.io.IOException;

import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.helsoft.mojo.api.PDEMojo;

/**
 * This mojo reads the file build.properties and copy to the target/classes
 * directory the resources under the properties <code>build.properties</code>.
 * It's also copy jars described into the manifest under the properties
 * <code>Bundle-Version</code>.
 * 
 * @author steg
 * 
 * @goal update-package
 * 
 * @phase generate-resources
 */
public class UpdatePackageMojo extends PDEMojo {

	/**
	 * @parameter expression="${project.resources.directory}" default-value="src/main/resources"
	 * @readonly
	 */
	private File resourceDir;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		// We add resources from bin.includes of the build.properties
		String[] binIncludes = getBuildProperties()
				.getProperty("bin.includes", "").trim().split("\\s*,\\s*");
		for (String path : binIncludes) {
			File file = new File(path);
			addResource(file);
		}
		// We add resources from Bundle-Classpath of the manifest
		for (String classpathEntry : getPluginDescriptor().getBundleClasspath()) {
			File file = new File(classpathEntry.trim());
			addResource(file);
		}
	}

	private void addResourceFile(File file) {
		if (!isInResourceDirectory(file)) {
			String parent = file.getParent();
			Resource rc = new Resource();
			rc.setFiltering(true);
			rc.setDirectory(parent == null ? "" : parent);
			rc.setTargetPath(parent);
			rc.addInclude(file.getName());
			project.addResource(rc);
		}
	}

	private void addResourceDirectory(File dir) {
		if (!isInResourceDirectory(dir) && !".".equals(dir.getPath())
				&& !dir.equals(project.getBasedir())) {
			Resource rc = new Resource();
			rc.setDirectory(dir.getPath());
			rc.setTargetPath(dir.getPath());
			project.addResource(rc);
		}
	}

	private void addResource(File file) {
		if (file.isFile()) {
			addResourceFile(file);
		} else if (file.isDirectory()) {
			addResourceDirectory(file);
		}
	}

	public final boolean isInResourceDirectory(File file) {
		try {
			String left = file.getCanonicalPath();
			String right = resourceDir.getCanonicalPath();
			return left.startsWith(right);
		} catch (IOException e) {
			getLog().debug(e);
			return false;
		}
	}
	
	public final boolean isInSourceFolder(File file) {
		try {
			String left = file.getCanonicalPath();
			String right = new File(project.getBuild().getSourceDirectory()).getCanonicalPath();
			return left.startsWith(right);
		} catch (IOException e) {
			getLog().debug(e);
			return false;
		}
	}
	
}
